package com.usian.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.behavior.mapper.ApBehaviorEntryMapper;
import com.usian.behavior.mapper.ApFollowBehaviorMapper;
import com.usian.behavior.service.ApBehaviorEntryService;
import com.usian.behavior.service.ApFollowBehaviorService;
import com.usian.model.behavior.dtos.FollowBehaviorDto;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.behavior.pojos.ApFollowBehavior;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApFollowBehaviorServiceImpl extends ServiceImpl<ApFollowBehaviorMapper, ApFollowBehavior> implements ApFollowBehaviorService {

    @Autowired
    private ApFollowBehaviorMapper apFollowBehaviorMapper;

    @Autowired
    private ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    private ApBehaviorEntryMapper apBehaviorEntryMapper;

    @Override/*保存 关注行为*/
    public ResponseResult saveFollowBehavior(FollowBehaviorDto dto) {

        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        /*先根据用户的id 去查询  一个实体   因为关注行为表里的entry_id 是查出来的实体主键*/
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryMapper.findApBehaviorEntry(dto.getUserId(), null);
        if (apBehaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"实体不存在");
        }

        /*保存关注行为之前 先去关注行为表里去查  查不到再添加*/
        List<ApFollowBehavior> list = apFollowBehaviorMapper.selectList(Wrappers.<ApFollowBehavior>lambdaQuery().eq(ApFollowBehavior::getEntryId, apBehaviorEntry.getId())
                .eq(ApFollowBehavior::getArticleId, dto.getArticleId()).eq(ApFollowBehavior::getFollowId, dto.getFollowId()));

        if (list.size()==0){
            //保存关注行为
            ApFollowBehavior apFollowBehavior = new ApFollowBehavior();
            apFollowBehavior.setEntryId(apBehaviorEntry.getId());
            apFollowBehavior.setCreatedTime(new Date());
            apFollowBehavior.setArticleId(dto.getArticleId());
            apFollowBehavior.setFollowId(dto.getFollowId());
            apFollowBehaviorMapper.saveApFollowBehavior(apFollowBehavior);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }
}
